package com.aloda.ojgateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.aloda.ojcommon.constant.RedisConstant;
import com.aloda.ojcommon.properties.TokenProperties;
import com.aloda.ojgateway.properties.AuthProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * 登录权限校验过滤器
 *
 * @Author aloda
 * @Date 2025/4/24 20:36
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private AuthProperties authProperties;

    @Resource
    private TokenProperties tokenProperties;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获得用户信息
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否放行路径
        if (isExclude(request.getPath().toString())) {
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 3.获取token
        String token = null;
        List<String> headers = request.getHeaders().get(tokenProperties.getUserTokenName());
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }
        // 4.校验并解析token
        String key = RedisConstant.USER_TOKEN + token;
        String userInfo = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(userInfo)) {
            // 拦截，设置响应状态码为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }

    /**
     * 利用spring的AntPathMatcher判断路径是否为拦截路径
     *
     * @param path
     * @return
     */
    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }
}
